package com.my.ads.lib.activity;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.BatteryManager;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.my.ads.lib.AdSummary;
import com.my.ads.lib.Config;
import com.my.ads.lib.bean.DataBean;
import com.my.ads.lib.listen.PowerInfoReceiver;
import com.my.ads.lib.utils.Utils;
import com.my.ads.lib.view.CoreFlashTextView;
import com.rapid.clean.deep.R;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

/**
 * Created by xuanyang on 2018/3/6.
 */

public class PowerActivity extends BaseActivity {

    private TextView my_time, my_date, my_week, text_charging, lock_cpu, lock_battery, lock_temperature;
    private ImageView img_lock_gift, img_menu;
    private CoreFlashTextView bottom_action;
    private PowerInfoReceiver myBroadcastReceiver;
    private IntentFilter intentFilter;
    public static boolean isLocked = false;

    private RelativeLayout container;
    private PopupWindow pw;
    private LayoutInflater inflater;

    private boolean mIsGet = true;
    private double BatteryT;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_DISMISS_KEYGUARD);
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED);
        setContentView(R.layout.power_activity);


        initViews();
        //订阅
        EventBus.getDefault().register(this);

        img_menu.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
                View view = inflater.inflate(R.layout.menu_layout, null);
                TextView textView = (TextView) view.findViewById(R.id.text_off);
                pw = new PopupWindow(view, RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
                pw.setFocusable(true);
                textView.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        finish();
                    }
                });
                pw.showAsDropDown(img_menu);
            }
        });
        registerReceiver(mBatInfoReceiver, new IntentFilter(Intent.ACTION_BATTERY_CHANGED));


        //注册广播
        myBroadcastReceiver = new PowerInfoReceiver();
        intentFilter = new IntentFilter();
        intentFilter.addAction(Intent.ACTION_TIME_TICK);
        intentFilter.addAction(Intent.ACTION_DATE_CHANGED);
        intentFilter.addAction(Intent.ACTION_BATTERY_CHANGED);
        registerReceiver(myBroadcastReceiver, intentFilter);

        isLocked = true;
        img_lock_gift.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent startMain = new Intent(Intent.ACTION_MAIN);
                startMain.addCategory(Intent.CATEGORY_HOME);
                startMain.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                startActivity(startMain);
                AdSummary.getInstance().showInterstitialAd(PowerActivity.this, 0, "");
                finish();
            }
        });

        try {
            ad(this);
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    @Override
    public void onBackPressed() {
        quitActivity();
    }


    @Override
    public void onResume() {
        super.onResume();


        my_time.setText(getSystemTime());
        my_date.setText(getSystemDate());
        my_week.setText(getSystemWeek());

        long l = Utils.getAvailMemory(PowerActivity.this);
        long y = Utils.getTotalMemory(PowerActivity.this);
        final double x = (((y - l) / (double) y) * 100);
        lock_cpu.setText(String.valueOf((int) (x)) + "%");

        try {
            ad(this);
        } catch (Exception e) {
            e.printStackTrace();
        }


    }

    private void initViews() {
        lock_temperature = (TextView) findViewById(R.id.lock_temperature);
        lock_battery = (TextView) findViewById(R.id.lock_battery);
        lock_cpu = (TextView) findViewById(R.id.lock_cpu);
        lock_cpu.setText("60%");
        img_menu = (ImageView) findViewById(R.id.img_menu);
        my_time = (TextView) findViewById(R.id.tv_time);
        my_date = (TextView) findViewById(R.id.tv_year_time);
        my_week = (TextView) findViewById(R.id.week);
        text_charging = (TextView) findViewById(R.id.text_charging);


        bottom_action = (CoreFlashTextView) findViewById(R.id.bottom_action);

        container = (RelativeLayout) findViewById(R.id.root_1);
        img_lock_gift = (ImageView) findViewById(R.id.img_lock_gift);

    }

    //获取电池温度
    private BroadcastReceiver mBatInfoReceiver = new BroadcastReceiver() {
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            /*
             * 如果捕捉到的action是ACTION_BATTERY_CHANGED，就运行onBatteryInfoReceiver()
             */
            if (Intent.ACTION_BATTERY_CHANGED.equals(action)) {

                if (mIsGet) {
                    BatteryT = intent.getIntExtra("temperature", 0);  //电池温度
                    lock_temperature.setText(((int) BatteryT / 10) + "℃");
                }
            }

        }
    };

    private String getSystemTime() {
        long time = System.currentTimeMillis();
        SimpleDateFormat format = new SimpleDateFormat("HH:mm");
        Date date = new Date(time);
        String s = format.format(date);
        return s;
    }

    private String getSystemDate() {
        long time = System.currentTimeMillis();
        SimpleDateFormat format = new SimpleDateFormat("yyyy/MM/dd");
        Date date = new Date(time);
        String s = format.format(date);
        return s;
    }

    private String getSystemWeek() {
        Calendar c = Calendar.getInstance();
        String mWay = String.valueOf(c.get(Calendar.DAY_OF_WEEK));
        if ("1".equals(mWay)) {
            mWay = "(Sun)";
        } else if ("2".equals(mWay)) {
            mWay = "(Mon)";
        } else if ("3".equals(mWay)) {
            mWay = "(Tue)";
        } else if ("4".equals(mWay)) {
            mWay = "(Wed)";
        } else if ("5".equals(mWay)) {
            mWay = "(Thu)";
        } else if ("6".equals(mWay)) {
            mWay = "(Fri)";
        } else if ("7".equals(mWay)) {
            mWay = "(Sat)";
        }
        return mWay;
    }

    @Subscribe(threadMode = ThreadMode.MAIN) //在ui线程执行
    public void mEvent(DataBean event) {
        if (!TextUtils.isEmpty(event.getMsg())) {
            switch (event.getMsg()) {
                case Config.EventTime:
                    my_time.setText(getSystemTime());
                    break;
                case Config.EventDate:
                    my_date.setText(getSystemDate());
                    my_week.setText(getSystemWeek());
                    break;
                case Config.EventPower:
                    lock_battery.setText(String.valueOf(event.getProgress() + "%"));
                    int status = event.getStatus();
                    switch (status) {
                        case BatteryManager.BATTERY_STATUS_CHARGING:
                            bottom_action.setText(getResources().getText(R.string.charging));
                            break;
                        case BatteryManager.BATTERY_STATUS_FULL:
                            bottom_action.setText(getResources().getText(R.string.already_full));
                            break;
                        case BatteryManager.BATTERY_STATUS_DISCHARGING:
                        case BatteryManager.BATTERY_STATUS_NOT_CHARGING:
                        default:
                            bottom_action.setText(getResources().getText(R.string.uncharged));
                            break;
                    }
                    break;
            }
        }
    }


    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {

        if ((keyCode == KeyEvent.KEYCODE_HOME)) {
            return true;
        }
        quitActivity();
        return super.onKeyDown(keyCode, event);
    }

    @Override
    public void onAttachedToWindow() {
        super.onAttachedToWindow();
    }


    @Override
    public void onDestroy() {
        super.onDestroy();
        //取消订阅
        EventBus.getDefault().unregister(this);
        unregisterReceiver(myBroadcastReceiver);
        unregisterReceiver(mBatInfoReceiver);
    }

    private void ad(Context context) {
        AdSummary.getInstance().showNativeAd(PowerActivity.this, container, true);
    }

    private void quitActivity() {
        Intent startMain = new Intent(Intent.ACTION_MAIN);
        startMain.addCategory(Intent.CATEGORY_HOME);
        startMain.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        startActivity(startMain);
        AdSummary.getInstance().showInterstitialAd(this, 0, "");
        finish();
    }



}
